package com.lynn.blog.interceptor;

import com.lynn.blog.common.TokenHolder;
import com.lynn.blog.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Author: Lynn
 * Date: 2024/07/15 下午5:58
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private static final String AUTHORIZATION_HEADER = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(AUTHORIZATION_HEADER);
        if (token != null && !token.isEmpty()) {
            boolean b = JwtUtil.verifyToken(token);
            if (b) {
                TokenHolder.setToken(token);
                log.info("userId: {}, username: {}, token: {}", JwtUtil.getUserIdFromToken(token), JwtUtil.getUsernameFromToken(token), token);
                return true;
            }
            throw new RuntimeException("token无效。");
        }
        throw new RuntimeException("token不能为空，请登录。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TokenHolder.clear();
    }
}
